#include "../include/salary_handler.h"
#include "../include/db_manager.h"
#include <jsoncpp/json/json.h>
#include <iostream>

std::string SalaryHandler::getAllSalaries() {
    DBManager& db = DBManager::getInstance();
    
    std::string query = "SELECT * FROM salary ORDER BY Employee_id, Year DESC, Month DESC";
    auto results = db.executeSelectQuery(query);
    
    Json::Value response;
    response["success"] = true;
    response["data"] = Json::Value(Json::arrayValue);
    
    for (const auto& row : results) {
        Json::Value salary;
        salary["employee_id"] = row.at("Employee_id");
        salary["year"] = row.at("Year");
        salary["month"] = row.at("Month");
        salary["basic_pay"] = row.at("Basic_pay");
        salary["yingfa_pay"] = row.at("Yingfa_pay");
        salary["butie_pay"] = row.at("Butie_pay");
        salary["kouchu_pay"] = row.at("Kouchu_pay");
        salary["shifa_pay"] = row.at("Shifa_pay");
        salary["status"] = row.at("S_status");
        
        response["data"].append(salary);
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string SalaryHandler::getSalaryById(const std::string& id) {
    // 工资表使用复合主键，这里简化处理
    return getAllSalaries();
}

std::string SalaryHandler::addSalary(const std::string& data) {
    Json::Value request_data;
    Json::Reader reader;
    
    if (!reader.parse(data, request_data)) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "数据格式错误";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    DBManager& db = DBManager::getInstance();
    
    std::string query = std::string("INSERT INTO salary (Employee_id, Year, Month, Basic_pay, Yingfa_pay, Butie_pay, Kouchu_pay, Shifa_pay, S_status) VALUES ('") +
                       db.escapeString(request_data["employee_id"].asString()) + "', " +
                       request_data["year"].asString() + ", " +
                       request_data["month"].asString() + ", " +
                       request_data["basic_pay"].asString() + ", " +
                       request_data["yingfa_pay"].asString() + ", " +
                       request_data["butie_pay"].asString() + ", " +
                       request_data["kouchu_pay"].asString() + ", " +
                       request_data["shifa_pay"].asString() + ", '" +
                       db.escapeString(request_data["status"].asString()) + "')";
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "工资记录添加成功";
    } else {
        response["success"] = false;
        response["message"] = "工资记录添加失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string SalaryHandler::updateSalary(const std::string& id, const std::string& data) {
    // 解析复合主键：格式为 "employee_id:year:month"
    size_t pos1 = id.find(':');
    size_t pos2 = id.find(':', pos1 + 1);
    
    if (pos1 == std::string::npos || pos2 == std::string::npos) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "无效的工资记录ID格式";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    std::string employee_id = id.substr(0, pos1);
    std::string year = id.substr(pos1 + 1, pos2 - pos1 - 1);
    std::string month = id.substr(pos2 + 1);
    
    Json::Value request_data;
    Json::Reader reader;
    
    if (!reader.parse(data, request_data)) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "数据格式错误";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    DBManager& db = DBManager::getInstance();
    
    std::string query = std::string("UPDATE salary SET ") +
                       "Basic_pay = " + request_data["basic_pay"].asString() + ", " +
                       "Yingfa_pay = " + request_data["yingfa_pay"].asString() + ", " +
                       "Butie_pay = " + request_data["butie_pay"].asString() + ", " +
                       "Kouchu_pay = " + request_data["kouchu_pay"].asString() + ", " +
                       "Shifa_pay = " + request_data["shifa_pay"].asString() + ", " +
                       "S_status = '" + db.escapeString(request_data["status"].asString()) + "' " +
                       "WHERE Employee_id = '" + db.escapeString(employee_id) + 
                       "' AND Year = " + year + " AND Month = " + month;
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "工资记录更新成功";
    } else {
        response["success"] = false;
        response["message"] = "工资记录更新失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string SalaryHandler::deleteSalary(const std::string& id) {
    // 解析复合主键：格式为 "employee_id:year:month"
    size_t pos1 = id.find(':');
    size_t pos2 = id.find(':', pos1 + 1);
    
    if (pos1 == std::string::npos || pos2 == std::string::npos) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "无效的工资记录ID格式";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    std::string employee_id = id.substr(0, pos1);
    std::string year = id.substr(pos1 + 1, pos2 - pos1 - 1);
    std::string month = id.substr(pos2 + 1);
    
    DBManager& db = DBManager::getInstance();
    
    std::string query = "DELETE FROM salary WHERE Employee_id = '" + db.escapeString(employee_id) + 
                       "' AND Year = " + year + " AND Month = " + month;
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "工资记录删除成功";
    } else {
        response["success"] = false;
        response["message"] = "工资记录删除失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string SalaryHandler::getSalaryStatistics() {
    DBManager& db = DBManager::getInstance();
    
    auto results = db.executeSelectQuery("SELECT COUNT(*) as total FROM salary");
    int total_records = results.empty() ? 0 : std::stoi(results[0].at("total"));
    
    Json::Value response;
    response["success"] = true;
    response["total_records"] = total_records;
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string SalaryHandler::getSalaryByEmployee(const std::string& employee_id) {
    DBManager& db = DBManager::getInstance();
    
    std::string query = "SELECT * FROM salary WHERE Employee_id = '" + db.escapeString(employee_id) + "' ORDER BY Year DESC, Month DESC";
    auto results = db.executeSelectQuery(query);
    
    Json::Value response;
    response["success"] = true;
    response["data"] = Json::Value(Json::arrayValue);
    
    for (const auto& row : results) {
        Json::Value salary;
        salary["employee_id"] = row.at("Employee_id");
        salary["year"] = row.at("Year");
        salary["month"] = row.at("Month");
        salary["basic_pay"] = row.at("Basic_pay");
        salary["yingfa_pay"] = row.at("Yingfa_pay");
        salary["butie_pay"] = row.at("Butie_pay");
        salary["kouchu_pay"] = row.at("Kouchu_pay");
        salary["shifa_pay"] = row.at("Shifa_pay");
        salary["status"] = row.at("S_status");
        
        response["data"].append(salary);
    }
    
    Json::FastWriter writer;
    return writer.write(response);
} 